const mysql = require('mysql')
const { databaseConfig } = require('../config/database')
const { debug } = require('../config/app')
const pool = mysql.createPool(databaseConfig)
//返回一个Promise链接
const connectHandle = () => new Promise((resolve, reject) => {
  pool.getConnection((err, connection) => {
    if (err) {
      debug && console.error('链接错误：' + err.stack + '\n' + '链接ID：' + connection.threadId)
      reject(err)
    } else {
      debug && console.log('链接成功')
      resolve(connection)
    }
  })
})


async function querysql (sql) {
  const connection = await connectHandle()
  return new Promise((resolve, reject) => {
    try {
      debug && console.log(sql)
      connection.query(sql, (err, results) => {
        if (err) {
          reject(err)
        } else {
          resolve(results)
        }
      })
    } catch (err) {
      reject(err)
    } finally {
      connection.release()
    }
  })
}

module.exports = {
  querysql
}